package com.dz.lm.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 微信支付
 */
@Component
public class ScanCodeUtil {

    
    /**
    * 用于获取access_token
    * @param params
    * @param APIKEY 小程序id
    * @param SECRETKEY	小程序密钥
    * @return  access_token
    * @throws Exception*/

	public static String postToken() throws Exception {
		String APIKEY = "wx778cf37da0c2a209";// 小程序id
		String SECRETKEY = "a91cf821e389dd919ddfbff817d28cd4";// 小程序密钥
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
				+ APIKEY + "&secret=" + SECRETKEY;
		URL url = new URL(requestUrl); //打开和URL之间的连接
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		//设置通用的请求属性
		connection.setRequestMethod("GET");
		connection.setRequestProperty("Content-Type", "application/json");
		connection.setRequestProperty("Connection", "Keep-Alive");
		connection.setUseCaches(false);
		connection.setDoOutput(true);
		connection.setDoInput(true); 
		//得到请求的输出流对象
		DataOutputStream out = new DataOutputStream(connection.getOutputStream());
		out.writeBytes("");
		out.flush();
		out.close();
		// 建立实际的连接
		connection.connect();
		//定义 BufferedReader输入流来读取URL的响应
		BufferedReader in = null;
		if (requestUrl.contains("nlp"))
			in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
		else
			in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
		String result = "";
		String getLine;
		while ((getLine = in.readLine()) != null) {
			result += getLine;
		}
		in.close();
		JSONObject jsonObject = JSON.parseObject(result);
		String accesstoken = jsonObject.getString("access_token");
		return accesstoken;
	}

	/**	 
	* 生成带参小程序二维码	 
	* @param sceneStr	参数	 
	* @param accessToken	token	 
	*/	 
	public static void getminiqrQr(String sceneStr, String accessToken) {
		try {	            
			URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken);
			HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
			httpURLConnection.setRequestMethod("POST");// 提交模式
			//conn.setConnectTimeout(10000);//连接超时 单位毫秒
			//conn.setReadTimeout(2000);//读取超时 单位毫秒	            
			//发送POST请求必须设置如下两行
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setDoInput(true);	            
			//获取URLConnection对象对应的输出流
			PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());	            
			//发送请求参数
			JSONObject paramJson = new JSONObject();
			paramJson.put("scene", sceneStr);
			paramJson.put("page", "pages/home/home");
			paramJson.put("width", 430);
			paramJson.put("auto_color", true);
			/**	             
			 * line_color生效	             
			 * paramJson.put("auto_color", false);	             
			 * JSONObject lineColor = new JSONObject();	             
			 * lineColor.put("r", 0);	             
			 * lineColor.put("g", 0);	             
			 * lineColor.put("b", 0);	             
			 * paramJson.put("line_color", lineColor);	             
			 */
			printWriter.write(paramJson.toString());	            
			// flush输出流的缓冲	            
			printWriter.flush();	            
			//开始获取数据	            
			BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());	            
			OutputStream os = new FileOutputStream(new File("F:/upload/img/scanCode/2019-11-21/4.png"));	            
			int len = 0;
			byte[] arr = new byte[1024];
			while ((len = bis.read(arr)) != -1) {
				os.write(arr, 0, len);
				os.flush();		
			}
			os.close();
		} catch (Exception e) {
			e.printStackTrace();	    
		}
	}
	
	/**	 
	* 生成带参小程序二维码	 
	* @param sceneStr	参数	 
	* @param accessToken	token	 
	*/	 
	public static void getminiqrQr2(String sceneStr, String accessToken) {
		try {
	        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
	        HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken);  // 接口
	        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
			// 发送请求参数
			JSONObject paramJson = new JSONObject();
			paramJson.put("scene", sceneStr);
			paramJson.put("page", "pages/home/home");
			paramJson.put("width", 430);
			paramJson.put("auto_color", true);
			/**
			 * line_color生效
			 * paramJson.put("auto_color", false);
			 * JSONObject lineColor = new JSONObject();
			 * lineColor.put("r", 0);
			 * lineColor.put("g", 0);
			 * lineColor.put("b", 0);
			 * paramJson.put("line_color", lineColor);
			 */
	        String body = JSON.toJSONString(paramJson);//必须是json模式的 post      
	        StringEntity entity = new StringEntity(body);
	        entity.setContentType("image/png");
	        httpPost.setEntity(entity);
	        HttpResponse response = httpClient.execute(httpPost);
	        InputStream inputStream = response.getEntity().getContent();
			OutputStream os = new FileOutputStream(new File("F:/upload/img/scanCode/2019-11-21/4.png"));	            
			int len = 0;
			byte[] arr = new byte[1024];
			while ((len = inputStream.read(arr)) != -1) {
				os.write(arr, 0, len);
				os.flush();		
			}
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**	 
	* 生成带参小程序二维码	 
	* @param sceneStr	参数	 
	* @param accessToken	token	 
	*/	 
	public static Map<String, Object> getWxScanCode(String sceneStr, String accessToken, Object imgUrl) {
		Map<String, Object> retMap = new HashMap<String, Object>();
		try {
	        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
	        HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken);  // 接口
	        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
			// 发送请求参数
			JSONObject paramJson = new JSONObject();
			paramJson.put("scene", sceneStr);
			paramJson.put("page", "pages/home/home");
			paramJson.put("width", 430);
			paramJson.put("auto_color", true);
			/**
			 * line_color生效
			 * paramJson.put("auto_color", false);
			 * JSONObject lineColor = new JSONObject();
			 * lineColor.put("r", 0);
			 * lineColor.put("g", 0);
			 * lineColor.put("b", 0);
			 * paramJson.put("line_color", lineColor);
			 */
	        String body = JSON.toJSONString(paramJson);//必须是json模式的 post      
	        StringEntity entity = new StringEntity(body);
	        entity.setContentType("image/png");
	        httpPost.setEntity(entity);
	        HttpResponse response = httpClient.execute(httpPost);
	        InputStream inputStream = response.getEntity().getContent();
	        retMap = FileUploadUtil.uploadInStream(inputStream, imgUrl, "scanCode");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return retMap;
	}
	
	public static void main(String[] args){
		try {
			ScanCodeUtil.getWxScanCode("4", ScanCodeUtil.postToken(), "");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
